<template>
  <div id="swiper" :style="{'height': this.height + 'px'}">
    <div id="swiper-box"
         :style="{'width': boxWidth + 'px','height':boxHeight + 'px','transform':'translate(' + this.position + 'px,0)','transition': this.transition + 's'}">
      <swiper-item v-for="item in newData" :link="item.link" :image="item.image" :title="item.title"/>
    </div>
        <Progress :length="length" :flag="flag"></Progress>
  </div>
</template>

<script>
  import SwiperItem from "./SwiperItem";
  import Progress from "./Progress";

  export default {
    name: "Swiper",
    props: {
      moveTime: {
        type: Number | String,
        default: 2000
      },
      stopTime: {
        type: Number | String,
        default: 2000
      },
      data: Array
    },
    components: {
      Progress,
      SwiperItem
    },
    data() {
      return {
        width: 0,
        height: 0,
        boxWidth: 0,
        boxHeight: 0,
        length: 0,
        flag: 0,
        position: 0,
        timeout: null,
        newData: [],
        transition: 0
      }
    },
    methods: {
      setCenter(flag) {
        this.transition = 0
        let left = flag - 1, right = flag + 1
        let newData = []
        if (left < 0)
          left = this.length - 1
        if (right >= this.length)
          right = 0
        for (let i of [left, flag, right]) {
          newData.push(this.data[i])
        }
        this.newData = newData
        this.position = -this.width
      },
      init() {
        clearTimeout(this.timeout)
        this.width = document.body.clientWidth
        this.length = this.data.length
        this.height = this.width / 2
        this.boxWidth = 3 * this.width
        this.boxHeight = this.height
        this.position = -this.width
        this.move()
      },
      setTimeout() {
        // 使用timeout的好处是可以随时终止
        this.timeout = setTimeout(() => {
          this.transition = this.moveTime / 1000
          this.position = -this.width * 2
          this.flag += 1
          if (this.flag >= this.length)
            this.flag = 0
        }, this.stopTime)
      },
      move() {
        this.setCenter(this.flag)
        this.setTimeout()
      }
    },
    mounted() {
      window.addEventListener('resize', this.init)
      document.getElementById("swiper-box").addEventListener('transitionend', this.move)
    },
    activated() {
      this.init()
    }
  }
</script>

<style scoped>
  #swiper {
    width: 100%;
    overflow: hidden;
    position: relative;
  }

  #swiper-box {
    display: flex;
  }
</style>